#include "task.h"
#include "list.h"
#include <stddef.h>

#define TIME_SLICE_DEFAULT 5

// 全局变量定义
tcb tasks[TASK_COUNT];
int task_count = 0;
int task_running = 0;
int cur_task = -1;
int run_task;


// 就绪列表和阻塞列表定义
 list_t ready_list[6];  // 每个优先级一个就绪链表
static list_t block_list;

void task_list_init()
{
    for(int i = 0; i < 6; i++)
    {
        list_init(&ready_list[i]);
    }
    list_init(&block_list);
}

// 将任务添加到就绪队列
void task_add_to_ready(tcb *task) {
    if (task->priority >= 0 && task->priority < 6) {
        list_add_tail(&ready_list[task->priority], &task->node);
        task->state = TASK_STATE_READY;
    }
}

void remove_task_list(tcb *task)
{
    list_remove(&ready_list[task->priority], &task->node);
}

int get_stack(int task_index)
{
    return tasks[task_index].stack_ptr;
}

int get_next_task(void)
{
    int index = cur_task;
    index++;
    if (index >= task_count)
        index = 0;
    return index;
}

// 改进的任务创建
void create_task(task_function f, void *param, char *stack, int stack_len, int priority, const char *name) {
    if (task_count >= TASK_COUNT) return;
    
    int *top = (int *)(stack + stack_len);
    
    /* 伪造现场 */
    top -= 16;
    
    /* r4~r11 */
    for (int i = 0; i < 8; i++) top[i] = 0;
    
    /* r0~r3 */
    top[8]  = (int)param; /* r0 */
    top[9]  = 0; /* r1 */
    top[10] = 0; /* r2 */
    top[11] = 0; /* r3 */
    
    /* r12,lr */
    top[12] = 0; /* r12 */
    top[13] = 0; /* lr */
    
    /* 返回地址 */
    top[14] = (int)f;
    
    /* PSR */
    top[15] = (1<<24);
    
    /* 初始化 TCB */
    tcb *new_task = &tasks[task_count];
    new_task->priority = priority;
    new_task->stack_ptr = (int)top;
    new_task->state = TASK_STATE_READY;
    new_task->task_name = (char *)name;
    
    // 初始化链表节点
    new_task->node.prev = NULL;
    new_task->node.next = NULL;
    
    // 添加到就绪队列
    task_add_to_ready(new_task);
    
    task_count++;
}

void start_task(void)
{
    task_running = 1;
    while (1);
}

int is_task_running(void)
{
    return task_running;
}

void set_task_stack(int task, int sp)
{
    tasks[task].stack_ptr = sp;
}

int scheduler()
{
    for(int prio = 0; prio < 6; prio++)
    {
        if(!list_empty(&ready_list[prio]))
        {
            list_node_t *node = list_remove_head(&ready_list[prio]);
            tcb *task = (tcb *)((char *)node - offsetof(tcb, node));
            task->state = TASK_STATE_RUNNING;
            
            // 找到任务索引
            for (int i = 0; i < task_count; i++) {
                if (&tasks[i] == task) {
                    return i;
                }
            }
        }
    }
    return -1;
}